package com.xuecheng.content.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-03
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private CourseBaseService courseBaseService;

/*    //查询课程计划
    @Override
    public ResponseResult<TeachplanVo> treeNodes(Long id) {
        // 1.调用自定义mapper查询所有数据（包含三级数据）
        List<TeachplanVo> teachplanVos = teachplanMapper.treeNodes(id);
        //筛选出一级大纲
        TeachplanVo one = null;//一级大纲
        for (TeachplanVo teachplanVo : teachplanVos) {
            if (teachplanVo.getGrade().equals(1)) {
                one = teachplanVo;
                break;
            }
        }
        //筛选二级大纲
        List<TeachplanVo> twoList = new ArrayList<>();
        for (TeachplanVo teachplanVo : teachplanVos) {
            if (teachplanVo.getGrade().equals(2)) {
                twoList.add(teachplanVo);
            }
        }
        //将二级目录添加到一级目录中
        one.setTeachPlanTreeNodes(twoList);
        //遍历二级目录将三级小节放入二级目录
        if (twoList != null) {
            for (TeachplanVo two : twoList) {
                List<TeachplanVo> threeTeachplanVos = new ArrayList<>();
                for (TeachplanVo vo : teachplanVos) {
                    if (vo.getParentid().equals(two.getId())) {
                        threeTeachplanVos.add(vo);
                    }
                }
                //将三级设置到二级中
                two.setTeachPlanTreeNodes(threeTeachplanVos);
            }
        }
        //返回一级大纲
        return ResponseResult.okResult(one);
    }*/

    public ResponseResult<TeachplanVo> treeNodes(Long id) {
        //查询所有数据
        List<TeachplanVo> list = teachplanMapper.treeNodes(id);
        //筛选一级大纲 steam流
        TeachplanVo one = list.stream().filter(vo -> vo.getGrade().equals(1)).findFirst().get();
        //筛选二级目录
        List<TeachplanVo> twoList = list.stream().filter(vo -> vo.getGrade().equals(2)).collect(Collectors.toList());
        //将二级目录添加到一级中
        one.setTeachPlanTreeNodes(twoList);
        //筛选三级小节
        for (TeachplanVo teachplanVo : twoList) {
            List<TeachplanVo> threeList = list.stream().filter(vo -> vo.getParentid().equals(teachplanVo.getId())).collect(Collectors.toList());
            //将三级设置到二级中
            teachplanVo.setTeachPlanTreeNodes(threeList);
        }
        //返回一级大纲
        return ResponseResult.okResult(one);
    }

    //新增或修改课程内容（章节，小节）
    @Override
    public ResponseResult saveOrUpdateTeachplan(TeachplanDto dto) {
        //查询课程数据（为了校验课程状态）
        CourseBase courseBase = courseBaseService.getById(dto.getCourseId());
        // 2.校验课程状态(是否已发布)
        if (StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //将dto数据转为实体
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        //补充创建时间信息
        teachplan.setCreateDate(new Date());
        //如果添加或更新的是二级目录 手动设置父id
        if (teachplan.getGrade().equals(2)) {
            //通过前端传递的课程id和grade=1查询一级大纲
            Teachplan one = this.lambdaQuery().eq(Teachplan::getCourseId, dto.getCourseId())
                    .eq(Teachplan::getGrade, 1).one();
            Long oneId = one.getId();
            //手动设置父id
            teachplan.setParentid(oneId);
        }
        //如果添加或更新的是三级级目录 前端已传过来父id 不用手动设置
        //需要将章节数量进行+1(只有新增的时候让他走这里，所以加个条件 id是自动生成的 修改是有id的)
        if (teachplan.getId()==null&&teachplan.getGrade().equals(3)) {
            courseBase.setPlanNum(courseBase.getPlanNum() + 1);
            //更新数据库
            courseBaseService.updateById(courseBase);
        }
            //保存或更新数据库
            this.saveOrUpdate(teachplan);
        //修改课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        courseBaseService.updateById(courseBase);
        // 返回ok
        return ResponseResult.okResult();
    }
    @Override
    public ResponseResult deleteTeachplan(Long teachplanId) {
        // 1.查询课程计划
        Teachplan teachplan = this.getById(teachplanId);
        // 2.查询课程信息
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        // 3.校验课程状态（是否已提交 是否已发布 是否审核通过）
        if (StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_COMMIT_STATUS) ||
                StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PASTED_STATUS) ||
                StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        // 4.删除课程计划
        if (teachplan.getGrade().equals(2)) { // 二级删除
            // 查询该二级下是否有三级
            Long count = this.lambdaQuery()
                    .eq(Teachplan::getParentid, teachplan.getId()).count();
            // 判断如果有不能删除
            if (count>0) {
                throw new BusinessException(ErrorCode.DELETEERROR);
            }
            this.removeById(teachplanId);

        } else { // 三级删除
            // 课程章节数量-1
            courseBase.setPlanNum(courseBase.getPlanNum()-1);
            courseBaseService.updateById(courseBase);
            this.removeById(teachplanId);
        }
        // 5.返回ok
        return ResponseResult.okResult();

    }

}

